package ink.xiaobaibai.units;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @description: 图片验证码生成工厂
 * @author: 小白白
 * @create: 2021-05-13
 **/

public class ImageCodeFactory {

    /**
     * 设置图片背景
     */
    private static Color bgColor = new Color(255, 255, 255);
    private static final String[] FONTNAME = {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑"};
    private static final int[] FONTSIZE = {28, 32, 35, 39, 45};

    public ImageCodeFactory(String code, int w, int h) {
        this.random = new Random();
        this.code = code;
        this.w = w;
        this.h = h;
    }

    private Random random;
    private String code;
    private int w;
    private int h;

    private BufferedImage createImage() {
        /*
         * 1.创建图片
         * 2.设置背景色
         */
        BufferedImage img = new BufferedImage(this.w, this.h, BufferedImage.TYPE_INT_RGB);
        //设置画笔颜色
        Graphics2D graphics2d = (Graphics2D) img.getGraphics();
        graphics2d.setColor(bgColor);
        graphics2d.fillRect(0, 0, this.w, this.h);
        //填充图片大小的矩形（设置背景色）
        return img;
    }

    private Color randomColor() {
        int r = this.random.nextInt(256);
        int g = this.random.nextInt(256);
        int b = this.random.nextInt(256);
        return new Color(r, g, b);
    }

    private Font randomFont() {
        int index = this.random.nextInt(FONTNAME.length);
        //根据随机索引获取字体名
        String name = FONTNAME[index];
        //设置字体样式
        int style = this.random.nextInt(4);
        index = this.random.nextInt(FONTSIZE.length);
        //根据索引获取字体大小
        int size = FONTSIZE[index];
        return new Font(name, style, size);
    }

    private void drawLine(BufferedImage image) {
        int num = 3;
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        for (int i = 0; i < num; i++) {
            int x1 = this.random.nextInt(this.w);
            int y1 = this.random.nextInt(this.h);
            int x2 = this.random.nextInt(this.w);
            int y2 = this.random.nextInt(this.h);
            g2.setStroke(new BasicStroke(1.5F));
            g2.setColor(Color.BLUE);
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    public BufferedImage getImage() {
        /**
         * 写入字符（包括字符字体、颜色、字符种类）
         */
        BufferedImage img = this.createImage();
        Graphics g = img.getGraphics();

        for (int i = 0; i < this.code.length(); i++) {
            //设置画笔颜色
            g.setColor(this.randomColor());
            //设置画笔字体
            g.setFont(this.randomFont());
            //画出字符
            g.drawString(String.valueOf(this.code.charAt(i)).intern(), this.w / 4 * i, this.h - 5);
        }
        this.drawLine(img);
        return img;
    }

}